<template>
  <!-- 工单表表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="1000"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      v-loading="loading"
      element-loading-text="正在下达，请稍后..."
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="班制" prop="shiftSystemId">
            <el-select
              v-model="formData.shiftSystemId"
              placeholder="请选择班制"
              @change="changeShiftSet"
              clearable
            >
              <el-option
                v-for="item in shiftSetList"
                :key="item.id"
                :label="item.shiftSetName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划炉数">
            <el-input v-model="formData.stoveQuantity" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品名称">
            <el-input v-model="formData.materialCodeAndName" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="批次规则类型">
            <!--<el-select
              v-model="formData.batchRuleType"
              placeholder="请选择批次规则类型"
              disabled
            >
              <el-option
                v-for="item in batchRuleTypeList"
                :key="item.id"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>-->
          </el-form-item>
        </el-col>
      </el-row>
      <div class="table-header">
        <el-button
          v-if="!props.isReadonly"
          type="success"
          plain
          @click="handleAdd"
        >
          <i-ep-plus />
          新增</el-button
        >
      </div>
      <el-card shadow="never" class="table-container">
        <div class="formTable2">
          <el-table
            :data="formData.details"
            :key="Math.random"
            border
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column
              label="班次"
              prop="shiftName"
              min-width="100"
              show-overflow-tooltip
              align="center"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.shiftId'"
                  :rules="rules.shiftId"
                  label-width="0"
                >
                  <el-select
                    v-model="row.shiftId"
                    placeholder="请输入班次"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in shiftList"
                      :key="item.id"
                      :label="item.shiftCode"
                      :value="item.shiftId"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="计划炉数"
              prop="stoveCountNum"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.stoveCountNum'"
                  :rules="rules.stoveCountNum"
                  label-width="0"
                >
                  <el-input v-model="row.stoveCountNum" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="150"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="formData.details.length > 0"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >下 达</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESDAYPLANALLOCATINGORDER",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
const validateShift = (rule, value) => {
  const filter = formData.details.filter((item) => item.shiftId === value);
  if (filter.length > 1) {
    return Promise.reject("班次已存在");
  }
  return Promise.resolve();
};
const rules = reactive({
  shiftId: [
    { required: true, message: "请选择班次", trigger: "change" },
    { validator: validateShift, trigger: ["blur", "change"] },
  ],
  shiftSystemId: [{ required: true, message: "请选择班制", trigger: "change" }],
  stoveCountNum: [
    { required: true, message: "请输入计划炉数", trigger: "blur" },
    { validator: planQuantity, trigger: "blur" },
  ],
  shiftSystemId: [{ required: true, message: "请选择班制", trigger: "change" }],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  producePlanCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  workSequence: "",
  planNum: "",
  planDate: getCurrentDate(),
  planQuantity: "",
  planStatus: "",
  productionVersionNumber: "",
  externalCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  stoveQuantity: "",
  materialCodeAndName: "",
  shiftSystemId: "",
  details: [
    {
      id: "",
      shiftId: "",
      planDateId: "",
      stoveCountNum: "",
    },
  ],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        producePlanCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        workSequence,
        planNum,
        planDate,
        planQuantity,
        planStatus,
        productionVersionNumber,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
        stoveQuantity,
      } = newVal;
      Object.assign(formData, {
        id,
        producePlanCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        workSequence,
        planNum,
        planDate,
        planQuantity,
        planStatus,
        productionVersionNumber,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
        stoveQuantity,
      });
      if (newVal?.plantId) {
        getShiftSetList();
      }
      formData.materialCodeAndName =
        formData.materialName + "～" + formData.materialCode;
    }
  }
);
/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};
/** 删除行 */
const isValidated = ref(false);
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  shiftId: "",
  planDateId: "",
  stoveCountNum: "",
};
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.producePlanCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.workSequence = "";
  formData.planNum = "";
  formData.planDate = getCurrentDate();
  formData.planQuantity = "";
  formData.planStatus = "";
  formData.productionVersionNumber = "";
  formData.externalCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  formData.stoveQuantity = "";
  formData.materialCodeAndName = "";
  formData.shiftSystemId = "";
  shiftList.value = [];
  formData.details = [details];
  formData.details = [
    {
      id: "",
      shiftId: "",
      planDateId: "",
      stoveCountNum: "",
    },
  ];
}
const loading = ref(false);

/** 工单表保存提交 */
// async function handleSubmit() {
//   loading.value = true;
//   details.value.forEach((item, index) => {
//     item.workSequence = index + 1;
//   });
//   await request({
//     url: "/mes/mesdayplan/saveBatch",
//     method: "post",
//     data: details.value,
//   }).finally(() => {
//     loading.value = false;
//   });
//   ElMessage.success(`保存成功`);
//   closeDialog();
//   emit("reset-table", formData.id);
// }
/** 保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      console.log("formData", toRaw(formData));
      let sum = 0;
      formData.details.forEach((item) => {
        sum += item.stoveCountNum;
      });
      if (sum != formData.stoveQuantity) {
        ElMessage.error(`炉数总和与计划炉数不符`);
        return;
      }
      formData.listWorkingForm = formData.details;
      loading.value = true;
      await request({
        url: "/mes/mesdayplan/saveIssue",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`下达成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 获取当前日期yyyymmdd
function getCurrentDate() {
  const today = new Date();
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month + "-" + day;
}
//班制
const shiftSetList = ref([]);
async function getShiftSetList() {
  await request({
    url: "mes/messhiftset/getList",
    method: "post",
    data: { plantId: formData.plantId, enabled: 1 },
  }).then((res) => {
    shiftSetList.value = res.data;
  });
}
function changeShiftSet(val) {
  formData.shiftSystemId = val;
  formData.shiftId = "";
  shiftList.value = [];
  if (val) {
    getShifts();
  }
}

//班次
const shiftList = ref([]);
async function getShifts() {
  await request({
    url: "mes/messhiftset/getDetails",
    method: "post",
    data: {
      id: formData.shiftSystemId,
    },
  }).then((res) => {
    shiftList.value = res.data;
  });
}
function planQuantity(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^\d+(\.(0|5))?$/.test(value)) {
    callback(new Error("只能输入半炉"));
  } else if (Number(value) <= 0) {
    callback(new Error("请输入大于0的值"));
  } else {
    callback();
  }
}
</script>
